package com.sunlg.smarthome.contract.presenter;

import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.contract.SecurityDeviceContract;
import com.sunlg.smarthome.data.entity.SecurityDevice;
import com.sunlg.smarthome.data.remote.MySubscriber;
import com.sunlg.smarthome.data.remote.Result;
import com.sunlg.smarthome.data.remote.SHServiceWrapper;
import com.sunlg.smarthome.utils.PreferHelper;

import java.util.List;

/**
 * Created by sunlg on 2017/5/26.
 */

public class SecurityDevicePresenter implements SecurityDeviceContract.Presenter {

    private SHServiceWrapper mSHServiceWrapper;
    private SecurityDeviceContract.View mView;
    private PreferHelper preferHelper;

    public SecurityDevicePresenter() {
        mSHServiceWrapper = App.getInstance().getServiceWrapper();
        preferHelper = new PreferHelper(App.getInstance(), "gateway");
    }

    @Override
    public void deleteSecurityDevice(int deviceId) {
        mSHServiceWrapper.delSecurityDevice(deviceId, new MySubscriber<Result>() {
            @Override
            public void onSuccess(Result data) {
                if(data.getCode() == C.ActionStatus.SUCCESS){
                    if(data.getCode() == C.ActionStatus.SUCCESS){
                        loadAllSecurityDevice();
                    }else {
                        _onError(new Throwable(data.getMsg()));
                    }
                }
            }

            @Override
            public void _onError(Throwable e) {
                mView.showError(e.getMessage());
            }
        });
    }

    @Override
    public void loadAllSecurityDevice() {
        mSHServiceWrapper.getAllSecurityDevice(preferHelper.getInt("id", 0),
                new MySubscriber<Result<List<SecurityDevice>>>() {
            @Override
            public void onSuccess(Result<List<SecurityDevice>> data) {
                if(data.getCode() == C.ActionStatus.SUCCESS){
                    mView.hideNoneDeviceText();
                    mView.showSecurityDeviceList(data.getData());
                }else {
                    mView.showNoneDeviceText();
                    _onError(new Throwable(data.getMsg()));
                }
            }

            @Override
            public void _onError(Throwable e) {
                mView.showError(e.getMessage());
            }
        });
    }

    @Override
    public void attachView(SecurityDeviceContract.View view) {
        mView = view;
    }

    @Override
    public void dettachView() {
        mView = null;
    }
}
